<template>
	<div class="import">
		<preview-images ref="previewImages" />
		<BaseForm ref="BaseFormRef" type="qiye" />
		<el-card class="box-card">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold"
					>投保企业（上传营业执照可自动识别企业信息）</span
				>
			</div>
			<el-form
				:model="toubaoForm"
				:rules="rules"
				label-width="80px"
				ref="toubaoForm"
				v-loading="toubaoLoading"
			>
				<el-form-item label="营业执照" prop="businessLicense">
					<div style="display: flex; align-items: top; gap: 10px">
						<el-upload
							:class="{ 'hide-upload-button': toubaoForm.businessLicense }"
							:before-remove="toubaoBeforeRemove"
							:on-preview="() => onPreview(toubaoForm.businessLicense.url)"
							:limit="1"
							:http-request="handleToubaoUpload"
							:file-list="[toubaoForm.businessLicense].filter(Boolean)"
							list-type="text"
						>
							<span class="c-main"><i class="el-icon-plus"></i>点击上传</span>
						</el-upload>
						<!-- <a
							href="https://qtbx.meibaokeji.com.cn/employer/static/2022images/yyzz.png"
							>查看示例</a
						> -->
					</div>
				</el-form-item>
				<el-form-item label="企业名称" prop="customerName" required>
					<el-select
						v-model="toubaoForm.customerName"
						@change="(val) => getToubaoById(val)"
						size="mini"
						filterable
						:remote-method="remoteMethod"
						allow-create
						default-first-option
						style="display: block"
						placeholder="请选择企业"
					>
						<el-option
							v-for="customer in customerOptions"
							:value="customer.customerId"
							:label="customer.customerName"
						/>
					</el-select>
					<!-- <select-limit
						v-model="toubaoForm.customerName"
						@change="(val) => getToubaoById(val)"
						:options="customerOptions"
						value-key="customerId"
						label-key="customerName"
					></select-limit> -->
				</el-form-item>
				<el-form-item
					label="行业大类"
					prop="premiumMode"
					v-if="productData.premiumMode"
				>
					<el-select
						v-model="toubaoForm.premiumMode"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择行业大类"
					>
						<el-option
							v-for="mode in productData.premiumMode"
							:value="mode.value"
							:label="mode.name"
							:key="mode.value"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="单位性质" required>
					<el-select
						v-model="toubaoForm.manageNature"
						size="mini"
						filterable
						allow-create
						default-first-option
						class="field"
						placeholder="请选择"
						style="width: 100%"
					>
						<el-option
							v-for="idType in danweiOption"
							:key="idType.code"
							:value="idType.code"
							:label="idType.name"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="联系人" prop="contactName" required>
					<el-input
						v-model="toubaoForm.contactName"
						size="mini"
						placeholder="请输入联系人"
						class="field"
					/>
				</el-form-item>
				<el-form-item
					label="统一社会信用代码"
					prop="certNum"
					required
					label-width="132px"
				>
					<el-input
						v-model="toubaoForm.certNum"
						placeholder="请输入统一社会信用代码"
						size="mini"
						class="field"
					/>
				</el-form-item>

				<el-form-item label="手机号码" prop="contactPhone" required>
					<el-input
						v-model="toubaoForm.contactPhone"
						placeholder="请输入手机号码"
						size="mini"
						class="field"
					/>
				</el-form-item>
				<el-form-item label="所在地区" prop="area">
					<xh-address
						:value="toubaoForm.area"
						@value-change="({ value }) => (toubaoForm.area = value)"
					></xh-address>
				</el-form-item>
				<el-form-item label="详细地址" prop="address" required>
					<el-input
						v-model="toubaoForm.address"
						placeholder="请输入详细地址"
						size="mini"
						class="field"
					/>
				</el-form-item>

				<div style="grid-column: -1/1; text-align: center">
					<el-button size="small" type="primary" @click="saveToubao">
						确认
					</el-button>
				</div>
			</el-form>
		</el-card>
		<el-card class="box-card" v-if="showPerson" v-loading="personLoading">
			<div slot="header" class="clearfix">
				<span style="font-size: 16px; font-weight: bold">保障人员</span>
			</div>
			<insure-import
				:productId="productId"
				:start-time="qixianForm.startTime"
				:end-time="qixianForm.endTime"
				:businessId="businessId"
				@success="onSuccess"
			/>
		</el-card>
		<el-dialog
			append-to-body
			width="260px"
			:close-on-click-modal="false"
			:visible.sync="showCodePopup"
			title="扫码支付"
		>
			<img
				:src="codeImageUrl"
				style="height: 160px; width: 160px; display: block; margin: 0 auto"
			/>
			<div class="text-center fs_small mt-2">使用微信扫描上方二维码</div>
			<div slot="footer" style="text-align: right">
				<el-button
					v-if="canReceipt"
					size="mini"
					@click=";(showPayForm = true), (showCodePopup = false)"
					>我要线下转账</el-button
				>
				<el-button
					type="primary"
					size="mini"
					@click="payQuery"
					:loading="payQuerying"
					>我已支付</el-button
				>
			</div>
		</el-dialog>
		<el-dialog
			append-to-body
			width="350px"
			:close-on-click-modal="false"
			:visible.sync="showPayForm"
			title="线下支付"
		>
			<el-form :model="payForm" :rules="rules" ref="relationForm">
				<div class="c9 mb-1">代收保费帐户</div>
				<div class="mb-1">户名：富邦国际（厦门）保险经纪有限公司</div>
				<div class="mb-1">开户行：建设银行厦门厦大支行</div>
				<div class="mb-2">帐号：3515 0198 1701 0000 1011</div>

				<div class="c9 mb-1">提交支付凭证</div>
				<el-form-item prop="account" required>
					<XhFiles
						:value="payForm.bankElectronReceipt"
						@value-change="({ value }) => (payForm.bankElectronReceipt = value)"
						placeholder="上传支付凭证"
					/>
				</el-form-item>
			</el-form>
			<div slot="footer" style="text-align: right">
				<el-button
					size="mini"
					@click=";(showCodePopup = true), (showPayForm = false)"
					>返回扫码支付</el-button
				>
				<el-button
					type="primary"
					size="mini"
					@click="saveReceipt"
					:loading="receiptLoading"
					>提交支付凭证</el-button
				>
			</div>
		</el-dialog>
		<!-- <div style="margin-block: 20px; text-align: center">
			<el-button @click="save" type="primary" size="medium">保存</el-button>
		</div> -->
	</div>
</template>

<script>
import {
	productDetail,
	createBusiness,
	customerList,
	customerById,
	uploadFile,
	licenseOcr,
	sendSMSCode,
	saveInsure,
	saveBeibao,
	saveQixian,
	save,
	getBusinessById,
	saveReceipt
} from '@/api'
import { payQuery, goPay } from '@/api/order'
import _ from 'lodash'
import * as REGEXP from '@/const/REGEXP'
import { queryCitys, queryAreaByCode } from '@/api/form'
import moment from 'moment'
import XhAddress from '@/components/createCom/XhAddress.vue'
import XhFiles from '@/components/createCom/XhFiles.vue'
var urlSearchParams = new URLSearchParams(location.search)
var UrlSearch = {}
for (let [key, value] of urlSearchParams.entries()) {
	UrlSearch[key] = value
}
import { transformKey } from '@/utils'
import insureImport from '../components/insure-import.vue'
import BaseForm from '../components/BaseForm.vue'
const productId = 13253
const baoform = {
	customerId: '', // 企业的id
	customerName: '', // 企业名称
	certNum: '', // 统一代码
	area: {},
	address: '', // 详细地址
	contactName: '', // 联系人
	contactPhone: '', // 手机号
	businessLicense: '', // 营业执照
	code: '', // 验证码
	// provinceCode: '',
	cityCode: '',
	regionCode: '',
	//单位性质
	manageNature: ''
}
export default {
	data() {
		return {
			productData: {},
			sameAsToubao: true, // 被保企业同投保企业
			businessId: '',
			toubaoForm: Object.assign({}, baoform),
			toubaoBusinessLicenseFile: null,
			beibaoBusinessLicenseFile: null,
			toubaoLoading: false,
			beibaoLoading: false,
			rules: {
				customerName: [{ required: true, message: '请选择企业' }],
				certNum: [{ required: true, message: '请输入统一社会信用代码' }],
				address: [{ required: true, message: '请输入详细地址' }],
				manageNature: [{ required: true, message: '请选择单位性质' }],
				cityCode: [{ required: true, message: '请选择地市' }],
				regionCode: [{ required: true, message: '请选择区县' }],
				contactName: [{ required: true, message: '请输入联系人' }],
				contactPhone: [{ required: true, message: '请输入联系方式' }]
				// businessLicense: [{ required: true, message: '请上传营业执照' }]
			},
			customerOptions: [],

			danweiOption: [
				{
					code: '340',
					name: '私营'
				},
				{
					code: '330',
					name: '个体'
				},

				{
					code: '320',
					name: '集体'
				},
				{
					code: '310',
					name: '国有'
				},
				{
					code: '350',
					name: '三资'
				},
				{
					code: '351',
					name: '中外合资'
				},
				{
					code: '352',
					name: '中外合作'
				},
				{
					code: '353',
					name: '外商独资'
				},
				{
					code: '360',
					name: '混合所有制'
				},
				{
					code: '370',
					name: '合作'
				},
				{
					code: '380',
					name: '合伙'
				},
				{
					code: '390',
					name: '股份制企业'
				},
				{
					code: '400',
					name: '民营'
				},
				{
					code: '100',
					name: '机关、团体'
				},
				{
					code: '110',
					name: '国家机关'
				},
				{
					code: '118',
					name: '军队(武警)'
				},
				{
					code: '119',
					name: '使领馆'
				},
				{
					code: '120',
					name: '党政机关'
				},
				{
					code: '130',
					name: '社会团体'
				},
				{
					code: '140',
					name: '基层群众自治组织'
				},
				{
					code: '200',
					name: '事业单位'
				},
				{
					code: '210',
					name: '卫生事业'
				},
				{
					code: '220',
					name: '体育事业'
				},
				{
					code: '230',
					name: '社会事业'
				},
				{
					code: '240',
					name: '教育事业'
				},
				{
					code: '250',
					name: '文化艺术业'
				},
				{
					code: '260',
					name: '广播电影电视业'
				},
				{
					code: '270',
					name: '科学研究业'
				},
				{
					code: '280',
					name: '综合技术服务业'
				},
				{
					code: '300',
					name: '企业单位'
				},
				{
					code: '900',
					name: '其他'
				}
			],
			// 支付选择
			payForm: {
				bankElectronReceipt: []
			},

			codeImageUrl: '',
			showCodePopup: false,
			showPayForm: false,
			// 查询支付结果
			payQuerying: false,
			// 提交支付凭证
			receiptLoading: false,

			canReceipt: false // 允许公对公转账
		}
	},
	computed: {
		productId() {
			return 13253
		}
	},
	async created() {
		// if (this.productId == 13253) {
		// this.sameAsToubao = false
		// this.$set(this.beibaoForm, 'premiumMode', '')
		this.rules.premiumMode = [{ required: true, message: '请选择行业大类' }]
		// }
		var { businessId } = this.$route.query
		if (businessId) {
			this.fetchBusiness(businessId)
		}
		if (!businessId) {
			var servData = await createBusiness({
				productId,
				...UrlSearch
			}).then((res) => res.data)
			businessId = servData.businessId
		}
		this.businessId = businessId

		this.fetchCustomerOptions()

		productDetail(this.productId).then((res) => {
			this.productData = res.data
		})
	},
	mounted() {},
	watch: {
		sameAsToubao: {
			handler(same) {
				if (same) {
					this.beibaoForm = Object.assign({}, this.toubaoForm)
				}
			},
			immediate: false
		}
	},
	methods: {
		// 获取订单id
		fetchBusiness(businessId) {
			getBusinessById(businessId).then((res) => {
				if (res.data === '您已完成投保') {
					this.$router.replace({
						path: '/insure/pay-success',
						query: this.$route.query
					})
					return
				}
				this.toubaoForm = res.data.customer
				this.beibaoForm = res.data.relation
				this.qixianForm = {
					startTime: res.data.startTime,
					endTime: res.data.endTime
				}
				if (res.data.startTime && res.data.endTime) {
					this.showPerson = true
				}
			})
		},
		// 获取企业选项列表（ type 99 表示企业类型
		fetchCustomerOptions() {
			customerList({ type: 99 }).then((res) => {
				this.customerOptions = res.data
			})
		},
		// 投保成功回调
		async onSuccess() {
			// 二维码
			const { businessId } = this
			const { data: imageUrl, isWork: canReceipt } = await goPay({
				businessId,
				payType: 'pc'
			})
			this.codeImageUrl = imageUrl
			this.canReceipt = canReceipt
			this.showCodePopup = true
		},
		handleToubaoUpload({ file }) {
			uploadFile({ file, batchId: '' }).then((file) => {
				file.url = file.filePath
				licenseOcr(file).then((res) => {
					this.toubaoForm = Object.assign({}, baoform, res.data)
					this.toubaoForm.businessLicense = file
				})
			})
		},
		handleBeibaoUpload({ file }) {
			uploadFile({ file, batchId: '' }).then((file) => {
				file.url = file.filePath
				licenseOcr(file).then((res) => {
					this.beibaoForm = Object.assign({}, baoform, res.data)
					this.beibaoForm.businessLicense = file
				})
			})
		},
		toubaoBeforeRemove(file, filelist) {
			this.toubaoForm.businessLicense = null
		},
		beibaoBeforeRemove(file, filelist) {
			this.beibaoForm.businessLicense = null
		},
		getBeibaoById(id, type) {
			const isExist = this.customerOptions.find((customer) => {
				return customer.customerId === id
			})
			if (isExist) {
				this.beibaoForm.customerId = id
				customerById(id).then((res) => {
					if (res.data.businessLicense) {
						res.data.businessLicense.url = res.data.businessLicense?.filePath
					}
					this.beibaoForm = Object.assign({}, baoform, res.data)
				})
			} else {
				this.beibaoForm = Object.assign({}, baoform)
				this.beibaoForm.customerName = id
				this.$nextTick(this.$refs.beibaoForm.clearValidate)
			}
		},
		getToubaoById(id) {
			const isExist = this.customerOptions.find((customer) => {
				return customer.customerId === id
			})
			if (isExist) {
				this.toubaoForm.customerId = id
				this.toubaoForm.customerName = isExist.customerName
				customerById(id).then((res) => {
					if (res.data.businessLicense) {
						res.data.businessLicense.url = res.data.businessLicense?.filePath
					}
					this.toubaoForm = Object.assign({}, baoform, res.data)
				})
			} else {
				this.toubaoForm = Object.assign({}, baoform)
				this.toubaoForm.customerName = id
				this.$nextTick(this.$refs.toubaoForm.clearValidate)
			}
		},
		sendCode() {
			this.codeLoading = true
			sendSMSCode(this.toubaoForm.contactPhone)
				.then(() => {
					this.$message.success('验证码已发送')
				})
				.finally(() => {
					this.codeLoading = false
				})
		},
		saveToubao() {
			const postData = Object.assign({}, this.toubaoForm)
			postData.businessLicense = postData.businessLicense?.fileId
			this.$refs.toubaoForm.validate((valid) => {
				if (valid) {
					this.toubaoLoading = true
					saveInsure(postData, {
						type: 1,
						businessId: this.businessId
					}).finally(() => {
						this.toubaoLoading = false
					})
				}
			})
			this.saveQixian()
		},
		// saveBeibao() {
		// 	const postData = Object.assign({}, this.beibaoForm)
		// 	const { activePlan } = this.$refs.BaseFormRef.getValue()
		// 	postData.businessLicense = postData.businessLicense.fileId
		// 	postData.planId = activePlan.planId
		// 	this.$refs.beibaoForm.validate((valid) => {
		// 		if (valid) {
		// 			this.beibaoLoading = true
		// 			saveBeibao(postData, {
		// 				type: 2,
		// 				businessId: this.businessId
		// 			}).finally(() => {
		// 				this.beibaoLoading = false
		// 			})
		// 		}
		// 	})
		// },
		// 保险期限
		saveQixian() {
			const { startTime, period, endTime } = this.$refs.BaseFormRef.getValue()
			saveQixian(this.businessId, {
				startTime,
				endTime,
				period
			})
				.then(() => {
					this.qixianForm = {
						startTime,
						endTime
					}
					this.showPerson = true
				})
				.finally(() => {
					this.qixianLoading = false
				})
		},
		// 查结果
		payQuery() {
			this.payQuerying = true
			const { businessId } = this
			payQuery({ businessId })
				.then(() => {
					this.$router.push({
						path: '/13253/qiye-success',
						query: { businessId }
					})
					Recorder.submit({
						businessId
					})
				})
				.catch((res) => {
					this.$confirm(res.msg, '温馨提示', {
						showCancelButton: false
					})
				})
				.finally(() => {
					this.payQuerying = false
				})
		},
		// 提交凭证
		saveReceipt() {
			if (this.payForm.bankElectronReceipt.length === 0) {
				this.$message.error('请先上传凭证')
				return
			}
			const { businessId } = this
			this.receiptLoading = true
			saveReceipt(businessId, {
				bankElectronReceipt: this.payForm.bankElectronReceipt[0].batchId
			})
				.then(() => {
					this.$confirm('您的订单已提交成功', '温馨提示', {
						showCancelButton: false
					})
					// this.$router.push({ path: '/13253/success', query: { businessId } })
					Recorder.submit({
						businessId
					})
				})
				.finally(() => {
					this.receiptLoading = false
				})
		},
		onPreview(url) {
			this.$refs.previewImages.open(url)
		},
		remoteMethod(query) {}
	},
	components: { insureImport, XhAddress, XhFiles, BaseForm }
}
</script>

<style lang="scss" scoped="scoped">
.box-card {
	margin-bottom: 20px;
}

.product-name {
	font-size: 20px;
	font-weight: 600;
	text-align: center;
	margin-block: 20px;
}

.import ::v-deep {
	.el-form {
		display: grid;
		gap: 15px;
		grid-template-columns: 1fr 1fr;
	}

	.el-form-item {
		margin-bottom: 0;
	}

	.el-table__header tr th {
		font-size: 13px;
		color: #333;
		background: #fbfcff;
	}

	._error_ {
		color: #f22 !important;
	}
}

.field {
	width: 100%;
}

.append-fix {
	position: absolute;
	right: 1em;
	top: 50%;
	transform: translateY(-50%);
	color: #999;
}

.hide-upload-button ::v-deep .el-upload--picture-card {
	display: none;
}
</style>
